﻿#region License
/*
Copyright (c) 2012 TeX HeX (http://www.texhex.info/)

Permission is hereby granted, free of charge, to any person obtaining a copy of 
this software and associated documentation files (the "Software"), to deal in the 
Software without restriction, including without limitation the rights to use, copy, 
modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, 
and to permit persons to whom the Software is furnished to do so, subject to the 
following conditions:

The above copyright notice and this permission notice shall be included in all 
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, 
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 
*/
#endregion
using System;
using CommandLine;
using CommandLine.Text;
using System.IO;
using System.Text;

namespace OverlayMessageBoxLibrary
{
    public sealed class CommandLineExecutorResult
    {
        public bool Result = false;

        public string HelpText = String.Empty;

        public int ReturnCode = -9;
    }

    public sealed class CommandLineExecutor
    {
        #region Command Line Options class
        private sealed class CmdLineOptions
        {

            #region Helpscreen
            [HelpOption("?","Help", HelpText = "Shows this help screen.")]
            public string GetUsage()
            {

                HelpText help = new HelpText(ProgramBanner.FullBanner);
                help.MaximumDisplayWidth = 999;
                
                help.AddPreOptionsLine("Parameters:");
                help.AddOptions(this);                
                //help.AdditionalNewLineAfterOption = true;

                help.AddPostOptionsLine("Options:\r\n");
                help.AddPostOptionsLine("  <Symbol>: " + EnumHelper.GetOverlayMessageBoxSymbolsText());
                help.AddPostOptionsLine("  <ButtonSet>: " + EnumHelper.GetOverlayMessageBoxButtonSetText());

                help.AddPostOptionsLine("\r\nThe return code contains the value of the button the user has selected:\r\n");
                help.AddPostOptionsLine("  " + EnumHelper.GetOverlayMessageBoxButtonText());

                help.AddPostOptionsLine("\r\nExamples:\r\n");
                help.AddPostOptionsLine("  OverlayMessageBox --text \"My text\"");
                help.AddPostOptionsLine("  OverlayMessageBox --caption \"Title of message\" --text \"My text\" --symbol Warning");
                help.AddPostOptionsLine("  OverlayMessageBox --caption \"Title of message\" --text \"My text\" --headline \"The headline\" --symbol Error --buttonset RetryCancel");


                help.AddPostOptionsLine(String.Empty);

                return help.ToString();
            }
            #endregion


            [Option(null, "Text", HelpText = "Text to display in the message (use \\n for line breaks)", Required = true)]
            public string Text = "";

            [Option(null, "Symbol", HelpText = "A <Symbol> option that specifies which icon to display (default: Information)", Required = false)]
            public OverlayMessageBoxSymbol Symbol = OverlayMessageBoxSymbol.Information;

            [Option(null, "ButtonSet", HelpText = "A <ButtonSet> option that specifies which buttons to display (default: OK)", Required = false)]
            public OverlayMessageBoxButtonSet ButtonSet = OverlayMessageBoxButtonSet.OK;

            [Option(null, "Caption", HelpText = "Text to display in title of message", Required = false)]
            public string Caption = AssemblyInformationHelper.TitleAndVersion;

            [Option(null, "Headline", HelpText = "Text to display in the headline above the text (when set, a Task Dialog is used)", Required = false)]
            public string Headline = "";
                     
        }
        #endregion


        public CommandLineExecutorResult Execute(string[] CommandLineArguments)
        {
            CommandLineExecutorResult ret = new CommandLineExecutorResult();

            using (MemoryStream memStream = new MemoryStream())
            {
                TextWriter txtWriter = new StreamWriter(memStream);

                CommandLineParserSettings parserSettings = new CommandLineParserSettings(false, false, txtWriter);
                ICommandLineParser parser = new CommandLineParser(parserSettings);
                var cmdOptions = new CmdLineOptions();

                if (parser.ParseArguments(CommandLineArguments, cmdOptions))
                {
                    //Parsing OK, we can execute
                    OverlayMessageBoxSettings settings = new OverlayMessageBoxSettings();
                    settings.Caption = cmdOptions.Caption;
                    settings.Symbol = cmdOptions.Symbol;
                    settings.Text = FixLineBreaks(cmdOptions.Text);
                    settings.ButtonSet = cmdOptions.ButtonSet;
                    settings.Headline = cmdOptions.Headline;

                    OverlayMessageBoxButton retButton=OverlayMessageBox.Show(settings);

                    ret.ReturnCode = (int)retButton;
                    ret.Result = true;

                }
                else
                {
                    txtWriter.Flush();

                    ret.HelpText = MemoryStreamToString(memStream);
                }
            }

            return ret;
        }

        private string MemoryStreamToString(MemoryStream stream)
        {
            stream.Position = 0;
            var sr = new StreamReader(stream);
            return sr.ReadToEnd();
        }

        private string FixLineBreaks(string input)
        {
            //Replace CR/LF
            string temp = input.Replace("\\r\\n", "\r\n");
            //replace "lonely" \r or \n
            return temp.Replace("\\n", "\r\n").Replace("\\r", "\r\n");
        }


    }
}
